package org.hejw.rpc.client;

import org.hejw.rpc.discovery.ServiceInfoDiscoverer;
import org.hejw.rpc.info.ServiceInfo;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Random;

public class ClientStubInvocationHandler implements InvocationHandler {

    private Class<?> interf;

    private ServiceInfoDiscoverer serviceInfoDiscoverer;

    private NetClient netClient;

    private Random random = new Random();

    public ClientStubInvocationHandler(Class<?> interf, ServiceInfoDiscoverer serviceInfoDiscoverer,
                                       NetClient netClient) {
        this.interf = interf;
        this.serviceInfoDiscoverer = serviceInfoDiscoverer;
        this.netClient = netClient;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (method.getName().equals("toString")){
            return method.getClass().toString();
        }
        if(method.getName().equals("hashCode")){
            return 0;
        }
        //根据名称去注册中心找到对应的服务
        String serviceName = method.getName();
        List<ServiceInfo> serviceInfoList = serviceInfoDiscoverer.getServiceInfo(serviceName);
        ServiceInfo serviceInfo = serviceInfoList.get(random.nextInt(serviceInfoList.size()));
        //TODO: 将请求编组为消息发送到服务端，并读取服务端返回的结果

        return null;
    }
}
